import json

from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.contrib import auth
from django.contrib.auth.middleware import MiddlewareMixin
from django.http import HttpResponseForbidden
#NOT USE
class AuthenticationBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        username = request.GET.get('user')
        password = request.GET.get('password')
        # Get the user information from the LDAP if he can be authenticated
        # Get the user information from the LDAP if he can be authenticated
        # if get_LDAP_user(username, password) is None:
        #     return None
        if username is None or password is None:
            return None
        else:
            user = auth.authenticate(username=username, password=password)
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None
            # user = User(username=username)
            # user.is_staff = True
            # user.save()
        return user

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None




class AutomaticUserLoginMiddleware(MiddlewareMixin):

    def process_view(self, request, view_func, view_args, view_kwargs):

        if not AutomaticUserLoginMiddleware._is_user_authenticated(request):
            username = request.GET.get('username')
            # password = request.GET.get('password')
            # sign = data["sign"]
            if username:
                url = request.GET.get("url")
                print("URL in session is" + url)
                request.session["url"]=url
                user = User.objects.filter(username=username)[0]
                # user = auth.authenticate(username=username, password=u.password)
                if user is not None:
                    request.user = user
                    auth.login(request, user)
                    return

    @staticmethod
    def _is_user_authenticated(request):
        user = request.user
        return user and user.is_authenticated